package com.hxzy.interceptor;

import cn.hutool.json.JSONUtil;
import com.hxzy.common.annon.RepeatSubmit;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.ServletUtils;
import com.hxzy.common.vo.R;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 数据重复提交的拦截器(springmvc来实现的)
 *
 * @author tonneyyy
 */
@Component
public abstract class RepeatSubmitInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        //如果执行的不是Controller方法
        if (handler instanceof HandlerMethod) {

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //得到当前执行的方法
            Method method = handlerMethod.getMethod();
            // 判断方法上面是否有这个注解
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            //如果有注解
            if (annotation != null) {
                //如果是重复提交了
                if (this.isRepeatSubmit(request, annotation)) {
                    R r= R.build(AckCode.FAIL);
                    r.setMsg(annotation.message());

                    ServletUtils.renderString(response, JSONUtil.toJsonStr(r));
                    return false;
                }
            }
            return true;
        }
        else
        {
            return  true;
        }
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request
     * @return
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);


}
